from base.log  import logger
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

class BasePage:
    def __init__(self, driver):
        self.driver = driver
        self.wait = WebDriverWait(self.driver, 10)
        self.logger = logger  # 获取日志对象
        self.logger.debug("BasePage 初始化完成")

    def open(self, url):
        try:
            self.logger.debug("打开页面：%s" % url)
            self.driver.get(url)
            self.logger.info("已打开页面：%s" % url)
        except Exception as e:
            self.logger.error("打开页面失败：%s。错误信息：%s" % (url, str(e)))
            raise
    # 定位单个元素
    def find_element(self, locator):
        try:
            self.logger.debug("正在查找元素：%s" % str(locator))
            element = self.wait.until(EC.presence_of_element_located(locator))
            self.logger.info("找到元素：%s" % str(locator))
            return element
        except Exception as e:
            self.logger.error("查找元素失败：%s。错误信息：%s" % (str(locator), str(e)))
            raise

    def scroll_to_element(self, locator):
        """滚动到元素位置"""
        try:
            self.logger.debug("滚动到元素：%s" % str(locator))
            element = self.find_element(locator)
            self.driver.execute_script("arguments[0].scrollIntoView();", element)
            self.logger.info("已滚动到元素：%s" % locator)
            return element
        except Exception as e:
            self.logger.error("滚动到元素失败：%s。错误信息：%s" % (locator, str(e)))
            raise

    def click(self, locator):
        """点击元素"""
        try:
            self.logger.debug("点击元素：%s" % str(locator))
            element = self.find_element(locator)
            element.click()
            self.logger.info("已点击元素：%s" % str(locator))
        except Exception as e:
            self.logger.error("点击元素失败：%s。错误信息：%s" % (str(locator), str(e)))
            raise

    def send_keys(self, locator, text):
        """输入文本"""
        try:
            # 检查text是否为None，如果是，则可以跳过输入或者输入一个默认值
            if text is None:
                self.logger.warning("尝试向元素：%s 输入文本，但文本为None" % str(locator))
                # 可以选择跳过输入或者输入一个默认值
                # 例如，这里我们选择跳过输入
                return

            self.logger.debug("向元素：%s 输入文本：%s" % (str(locator), text))
            element = self.find_element(locator)
            element.send_keys(text)
            self.logger.info("已向元素：%s 输入文本：%s" % (str(locator), text))
        except Exception as e:
            self.logger.error("向元素输入文本失败：%s。错误信息：%s" % (str(locator), str(e)))
            raise

    def get_text(self, locator):
        """获取文本"""
        try:
            self.logger.debug("从元素：%s 获取文本" % str(locator))
            element = self.find_element(locator)
            text = element.text
            self.logger.info("从元素：%s 获取到文本：%s" % (str(locator), text))
            return text
        except Exception as e:
            self.logger.error("从元素获取文本失败：%s。错误信息：%s" % (str(locator), str(e)))
            raise

    def get_title(self):
        """获取标题"""
        try:
            self.logger.debug("获取页面标题")
            title = self.driver.title
            self.logger.info("页面标题：%s" % title)
            return title
        except Exception as e:
            self.logger.error("获取页面标题失败。错误信息：%s" % str(e))
            raise

    def switch_to_window_by_title(self, title):
        """通过标题切换窗口"""
        try:
            self.logger.debug("切换到标题为：%s 的窗口" % title)
            handles = self.driver.window_handles
            for handle in handles:
                self.driver.switch_to.window(handle)
                if self.get_title() == title:
                    self.logger.info("已切换到标题为：%s 的窗口" % title)
                    return
            self.logger.warning("未找到标题为：%s 的窗口" % title)
        except Exception as e:
            self.logger.error("切换到标题为：%s 的窗口失败。错误信息：%s" % (title, str(e)))
            raise

    def get_url(self):
        """获取当前页面的url"""
        try:
            self.logger.debug("获取当前页面的URL")
            url = self.driver.current_url
            self.logger.info("当前页面的URL：%s" % url)
            return url
        except Exception as e:
            self.logger.error("获取当前页面的URL失败。错误信息：%s" % str(e))
            raise

    def switch_to_frame(self, locator):
        """切换frame"""
        try:
            self.logger.debug("切换到frame：%s" % locator)
            self.driver.switch_to.frame(locator)
            self.logger.info("已切换到frame：%s" % locator)
        except Exception as e:
            self.logger.error("切换到frame：%s 失败。错误信息：%s" % (locator, str(e)))
            raise

    def switch_to_default_content(self):
        """退出frame"""
        try:
            self.logger.debug("退出frame")
            self.driver.switch_to.default_content()
            self.logger.info("已退出frame")
        except Exception as e:
            self.logger.error("退出frame失败。错误信息：%s" % str(e))
            raise

    def handle_alert(self, action: str = "accept"):
        """处理弹窗"""
        try:
            self.logger.debug("处理弹窗，操作：%s" % action)
            alert = self.driver.switch_to.alert
            if action.lower() == "accept":
                alert.accept()
                self.logger.info("已接受弹窗")
            elif action.lower() == "dismiss":
                alert.dismiss()
                self.logger.info("已取消弹窗")
        except Exception as e:
            self.logger.error("处理弹窗失败。错误信息：%s" % str(e))
            raise

    def back(self):
        try:
            self.logger.debug("后退页面")
            self.driver.back()
            self.logger.info("已后退页面")
        except Exception as e:
            self.logger.error("后退页面失败。错误信息：%s" % str(e))
            raise

    def forward(self):
        try:
            self.logger.debug("前进页面")
            self.driver.forward()
            self.logger.info("已前进页面")
        except Exception as e:
            self.logger.error("前进页面失败。错误信息：%s" % str(e))
            raise

    def refresh(self):
        try:
            self.logger.debug("刷新页面")
            self.driver.refresh()
            self.logger.info("已刷新页面")
        except Exception as e:
            self.logger.error("刷新页面失败。错误信息：%s" % str(e))
            raise
